package cn.janescott.zone.portal;

import cn.janescott.zone.data.dto.User;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

//@EnableCircuitBreaker
@EnableDiscoveryClient
@SpringBootApplication
@EnableFeignClients
@RestController
public class ZonePortalWebappApplication {

	public static void main(String[] args) {
		SpringApplication.run(ZonePortalWebappApplication.class, args);
	}

	@LoadBalanced
	@Bean("restTemplate")
	public RestTemplate restTemplate() {
		return new RestTemplate();
	}

	@Resource(name = "restTemplate")
	private RestTemplate rt;

	@GetMapping("/log")
	public void log() {
		rt.getForEntity("http://ZONE-DATA-PROVIDER/zone-data/log", void.class);
	}

	@GetMapping("/show")
	public String show() {
		return "i am alive";
	}

	@GetMapping("/redirect")
	public ModelAndView redirect(@ModelAttribute("ids")Long [] ids, RedirectAttributes attributes, ModelMap modelMap) {
	    List<Long> params = new ArrayList<>();
	    params.add(11111L);
	    params.add(2222L);
	    params.add(3333L);
		attributes.addAttribute("ids", params);
		modelMap.addAttribute("ids", params);
//        new RedirectView("actual",true,false,false);
		return new ModelAndView(new RedirectView("actual",true,false,false), modelMap);
	}

	@PostMapping("/actual")
	public String actual(@ModelAttribute("ids")List<Long> ids) {
		StringBuffer sb = new StringBuffer();
		for (Long id : ids) {
			sb.append(String.valueOf(id));
		}
		return sb.toString();
	}

	@RequestMapping("/memory")
	public void memory(HttpServletResponse response, Long[] ids, HttpServletRequest request, @RequestParam(name = "userDTO", required = false) List<User> users) throws Exception {
		System.out.printf("debug");
    }

}
